package com.laowang.project.system.controller;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.laowang.common.exception.CustomException;
import com.laowang.common.utils.DateUtils;
import com.laowang.common.utils.SecurityUtils;
import com.laowang.common.utils.StringUtils;
import com.laowang.framework.redis.RedisCache;
import com.laowang.framework.web.page.TableDataInfoMy;
import com.laowang.project.common.controller.CommonController;
import com.laowang.project.system.domain.*;
import com.laowang.project.system.domain.vo.LookObj;
import com.laowang.project.system.mapper.MyCarBookMapper;
import com.laowang.project.system.mapper.MyCyhCarMapper;
import com.laowang.project.system.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.laowang.framework.aspectj.lang.annotation.Log;
import com.laowang.framework.aspectj.lang.enums.BusinessType;

import com.laowang.framework.web.controller.BaseController;
import com.laowang.framework.web.domain.AjaxResult;
import com.laowang.common.utils.poi.ExcelUtil;
import com.laowang.framework.web.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;
import oshi.jna.platform.mac.SystemB;

/**
 * 车友通讯录Controller
 *
 * @author laowang
 * @date 2023-04-20
 */
@Api(tags = "车友通讯录接口")
@RestController
@RequestMapping("/carBook")
public class MyCarBookController extends BaseController {
    @Autowired
    private MyCarBookService myCarBookService;



    @Autowired
    private RedisCache redisCache;

    @Autowired
    private ISysDictTypeService dictTypeService;

    @Autowired
    private CommonController commonController;

    @Autowired
    private MyCarBookMapper myCarBookMapper;

    @Autowired
    private WxUserService wxUserService;

    @Autowired
    private UserPointLogService userPointLogService;

    @Autowired
    private MyCyhCarGroupService myCyhCarGroupService;

    @ApiOperation(value = "小程序端 车友通讯录发布",notes = "")
    @PostMapping("/publish")
    public AjaxResult publish(@Validated @RequestBody MyCarBook myCarBook) {


        int i = myCarBookService.insertMyCarBookWeb(myCarBook);
        if (i == 0){
            return AjaxResult.error("已有通讯录,请勿重复添加");
        }

        return AjaxResult.success("操作成功");
    }

    @ApiOperation(value = "小程序端 回显身份证和驾驶证信息",notes = "")
    @PostMapping("/getInfo")
    public AjaxResult getInfo(MultipartFile file, Integer type) {
        if (!type.equals(1) && !type.equals(2) && !type.equals(3) && !type.equals(4)){
            return AjaxResult.error("类型不匹配");
        }
        AjaxResult upload = commonController.upload(file);
        int code = (int) upload.get("code");
        if (code == 200){
            String data = (String) upload.get("data");
            Object info = myCarBookService.getInfo(data, type);
            return AjaxResult.success("操作成功",info);
        }else {
            return AjaxResult.error("上传失败");
        }

    }


    @ApiOperation(value = "小程序端 车友通讯录发布1",notes = "")
    @PostMapping("/publish1")
    public AjaxResult publish1( @RequestBody MyCarBook myCarBook) {

        int i = myCarBookService.insertMyCarBookWeb1(myCarBook);
        if (i == 0){
            return AjaxResult.error("已有通讯录,请勿重复添加");
        }
        return AjaxResult.success("操作成功");
    }

    /**
     * 查询车友通讯录列表
     */
    @ApiOperation(value = "小程序端 查询自己的车友信息",notes = "")
    @GetMapping("/web/myInfo")
    public AjaxResult myInfo( ) {
        Integer mid = SecurityUtils.getLoginUser().getWxUser().getMid();
        MyCarBook myCarBook = myCarBookService.selectMyCarBookByUserId(mid);

        return AjaxResult.success("操作成功",myCarBook);
    }


    @ApiOperation(value = "小程序端 绑定副牌",notes = "")
    @GetMapping("/web/bind")
    public AjaxResult myInfo(String subCard ) {
        if (StringUtils.isEmpty(subCard)){
            throw new CustomException("副牌为空",400);
        }
        Integer mid = SecurityUtils.getLoginUser().getWxUser().getMid();
        MyCarBook myCarBook = myCarBookService.selectMyCarBookByUserId(mid);
        if (myCarBook == null){
            throw new CustomException("请先认证通讯录",400);
        }
        myCarBook.setSubCard(subCard);
        myCarBookMapper.updateMyCarBook(myCarBook);
        return AjaxResult.success("操作成功",myCarBook);
    }

    /**
     * 查询车友通讯录列表
     */
    @ApiOperation(value = "小程序端 修改车友信息",notes = "")
    @PostMapping("/web/edit")
    public AjaxResult webedit(@RequestBody MyCarBook MyCarBook ) {
        myCarBookService.updateMyCarBookWeb(MyCarBook)    ;
        return AjaxResult.success("操作成功");
    }

    /**
     * 查询车友通讯录列表
     */
    @ApiOperation(value = "小程序端 查询车友通讯录列表",notes = "")
    @GetMapping("/web/list")
    public TableDataInfoMy weblist(MyCarBook myCarBook) {
        List<MyCyhCarGroup> myCyhCarGroups = myCyhCarGroupService.selectMyCyhCarGroupListWeb(null);
        Map<Integer, String> collect = myCyhCarGroups.stream().collect(Collectors.toMap(MyCyhCarGroup::getId, MyCyhCarGroup::getGroupName));
        startPage();
        List<MyCarBook> list = myCarBookService.selectMyCarBookListWeb(myCarBook);
        for (MyCarBook carBook : list) {
            if (StringUtils.isNotEmpty(carBook.getGroup()) && collect.containsKey(Integer.valueOf(carBook.getGroup()) )){
                carBook.setGroup(collect.get(Integer.valueOf(carBook.getGroup())));
            }
        }
        return getDataTableMy(list);
    }

    /**
     * 查询车友通讯录列表
     */
    @ApiOperation(value = "小程序端 查询车友信息",notes = "")
    @GetMapping("/web/carInfo")
    public AjaxResult carInfo(Integer userId,Integer needPoint ) {
        if (needPoint == null){
            return AjaxResult.error("是否积分查看参数不能为空");
        }
        if (!needPoint.equals(0) && !needPoint.equals(1)){
            return AjaxResult.error("是否积分查看参数不符合");
        }
        Integer mid = SecurityUtils.getLoginUser().getWxUser().getMid();
        WxUser wxUser = wxUserService.selectWxUserById(mid);
        MyCarBook myCarBook = myCarBookService.selectMyCarBookByUserId(userId);
        if (myCarBook == null){
            throw new CustomException("将要查看的通讯录不存在",400);
        }
        if (needPoint == 0){
            Integer n = 0;
            if (wxUser.getVipLevel() != null && wxUser.getExpireTime().after(new Date())){
                n =  wxUser.getVipLevel();
            }


            if ( n == 0 ){
                //没有会员的           没有副牌每天看一次
                LookObj lookObj = redisCache.getCacheObject("look:" + mid);
                if (Objects.isNull(lookObj)){
                    lookObj= new LookObj(new Date(), 1);
                    redisCache.setCacheObject("look:"+mid,lookObj,2, TimeUnit.DAYS);

                }else {
                    Date date = lookObj.getDate();
                    if (DateUtils.isSameDay(new Date(),date)){
                        return AjaxResult.success("非会员每天只能查看一次,是否需要积分查看");
                    }else {
                        lookObj= new LookObj(new Date(), 1);
                        redisCache.setCacheObject("look:"+mid,lookObj,2, TimeUnit.DAYS);
                    }
                }
            }
            if (n != 0){

                LookObj lookObj = redisCache.getCacheObject("look:" + mid);
                if (Objects.isNull(lookObj)){
                    lookObj= new LookObj(new Date(), 1);
                    redisCache.setCacheObject("look:"+mid,lookObj,2, TimeUnit.DAYS);

                }else {
                    Date date = lookObj.getDate();
                    if (DateUtils.isSameDay(new Date(),date)){
                        Integer num = lookObj.getNum();
                        if (n == 1){
                            // 一级会员 普通会员每天5次免费打招呼和20次查看，
                            if (num >= 20){
                                return AjaxResult.success("名车会员每天只能免费查看20次,是否需要积分查看");
                            }
                            num++;
                            LookObj  lookObj1 = new LookObj(new Date(), num);
                            redisCache.setCacheObject("look:"+mid,lookObj1,2, TimeUnit.DAYS);
                        }else if (n ==2){
                            //银牌会员每天10次打招呼和50次查看
                            if (num >= 50){
                                return AjaxResult.success("银牌会员每天只能查看50次,是否需要积分查看");
                            }
                            num++;
                            LookObj  lookObj1 = new LookObj(new Date(), num);
                            redisCache.setCacheObject("look:"+mid,lookObj1,2, TimeUnit.DAYS);
                        }else if (n == 3){
                            //金牌会员面体20次免费打招呼和100次查看
                            if (num >= 100){
                                return AjaxResult.success("金牌会员每天只能查看100次,是否需要积分查看");
                            }
                            num++;
                            LookObj  lookObj1 = new LookObj(new Date(), num);
                            redisCache.setCacheObject("look:"+mid,lookObj1,2, TimeUnit.DAYS);
                        }
                        // 其他的会员就不限制了

                    }else {
                        lookObj= new LookObj(new Date(), 1);
                        redisCache.setCacheObject("look:"+mid,lookObj,2, TimeUnit.DAYS);
                    }
                }
            }

        }else if (needPoint == 1){
            //用积分查看
            Integer points = wxUser.getPoints();
            if (points >= 100){
                //会员名额用完的情况或者非会员 100积分查看一次通讯录，500积分打一次招呼
                Integer  newpoints = points -100;
                wxUser.setPoints(newpoints);
                wxUserService.updateWxUser( wxUser);

                //积分日志
                UserPointLog userPointLog = new UserPointLog();
                userPointLog.setRemark("积分查看通讯录");
                userPointLog.setOldPoint(points);
                userPointLog.setChangePoint(-100);
                userPointLog.setNewPoint(newpoints);
                userPointLog.setUserId(mid);
                userPointLog.setType(6);//积分查看通讯录
                userPointLog.setCreated(new Date());
                userPointLogService.insertUserPointLog(userPointLog);
            }else {
                return AjaxResult.success("积分不足100");

            }
        }


        //WxUser wxUser1 = wxUserService.selectWxUserById(userId);
        myCarBook.setFupai(myCarBook.getSubCard());
        return AjaxResult.success("操作成功",myCarBook);
    }


    /**
     * 查询车友通讯录列表
     */
    @ApiOperation(value = "查询车友通讯录列表",notes = "")
    @PreAuthorize("@ss.hasPermi('my:carBook:list')")
    @GetMapping("/list")
    public TableDataInfo list(MyCarBook myCarBook) {

        List<MyCyhCarGroup> myCyhCarGroups = myCyhCarGroupService.selectMyCyhCarGroupListWeb(null);
        Map<Integer, String> collect = myCyhCarGroups.stream().collect(Collectors.toMap(MyCyhCarGroup::getId, MyCyhCarGroup::getGroupName));

        startPage();
        List<MyCarBook> list = myCarBookService.selectMyCarBookList(myCarBook);
        List<SysDictData> position_name = dictTypeService.selectDictDataByType("position_name");

        for (MyCarBook carBook : list) {
            for (SysDictData sysDictData : position_name) {
                if ( StringUtils.isNotEmpty(carBook.getPosition()) && carBook.getPosition().equals(sysDictData.getDictLabel())){
                    carBook.setPosition(sysDictData.getDictValue());
                }
            }


            if (StringUtils.isNotEmpty(carBook.getGroup()) && collect.containsKey(Integer.valueOf(carBook.getGroup()) )){
                carBook.setGroup(collect.get(Integer.valueOf(carBook.getGroup())));

            }
        }
        return getDataTable(list);
    }

    /**
     * 导出车友通讯录列表
     */
    @ApiOperation(value = "导出车友通讯录列表",notes = "")
    @PreAuthorize("@ss.hasPermi('my:carBook:export')")
    //@Log(title = "车友通讯录", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(MyCarBook myCarBook) {
        List<MyCarBook> list = myCarBookService.selectMyCarBookList(myCarBook);
        ExcelUtil<MyCarBook> util = new ExcelUtil<MyCarBook>(MyCarBook.class);
        return util.exportExcel(list, "carBook");
    }

    /**
     * 获取车友通讯录详细信息
     */
    @ApiOperation(value = "获取车友通讯录详细信息",notes = "")
    @PreAuthorize("@ss.hasPermi('my:carBook:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Integer id) {
        return AjaxResult.success(myCarBookService.selectMyCarBookById(id));
    }

    /**
     * 新增车友通讯录
     */
    @ApiOperation(value = "新增车友通讯录",notes = "")
    @PreAuthorize("@ss.hasPermi('my:carBook:add')")
    //@Log(title = "车友通讯录", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody MyCarBook myCarBook) {
        return toAjax(myCarBookService.insertMyCarBook(myCarBook));
    }

    /**
     * 修改车友通讯录
     */
    @ApiOperation(value = "修改车友通讯录",notes = "")
    @PreAuthorize("@ss.hasPermi('my:carBook:edit')")
    //@Log(title = "车友通讯录", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody MyCarBook myCarBook) {
        return toAjax(myCarBookService.updateMyCarBook(myCarBook));
    }

    /**
     * 删除车友通讯录
     */
    @ApiOperation(value = "删除车友通讯录",notes = "")
    @PreAuthorize("@ss.hasPermi('my:carBook:remove')")
    //@Log(title = "车友通讯录", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Integer[] ids) {
        return toAjax(myCarBookService.deleteMyCarBookByIds(ids));
    }
}
